import os
from openpyxl import Workbook

# 指定路径
path = r'D:\project\get_uid\data\FBB-4462'
output_name = 'FBB-4462.xlsx'
output_dir = os.path.join(r"D:\project\get_uid\output", output_name)


# 创建Excel文件
wb = Workbook()
ws = wb.active

# 设置表头
ws['A1'] = '文件夹名称'
ws['B1'] = 'UID内容'

# 遍历指定路径下的所有文件夹和文件
for root, dirs, files in os.walk(path):
    for file in files:
        # 判断文件名是否为UID.dat
        if file == 'UID.dat':
            # 获取文件夹名称
            folder_name = os.path.basename(root)
            
            # 读取文件内容
            file_path = os.path.join(root, file)
            with open(file_path, 'r') as f:
                uid_content = f.read()
            
            # 写入Excel
            row = [folder_name, uid_content]
            ws.append(row)

# 设置列宽
for column in ws.columns:
    max_length = 0
    column = [cell for cell in column]
    for cell in column:
        try:
            if len(str(cell.value)) > max_length:
                max_length = len(cell.value)
        except:
            pass
    adjusted_width = (max_length + 2) * 1.1
    ws.column_dimensions[column[0].column_letter].width = adjusted_width
# 保存Excel文件
wb.save(output_dir)
